<?php
/**
 * Created by PhpStorm.
 * User: 86151
 * Date: 2023/5/19
 * Time: 16:44
 */

namespace app\api\controller;
use app\common\controller\Api;
use think\Config;
use think\Db;
use liyijun\RSAUtils;
use app\admin\model\Auth;
use app\admin\model\WeChatPay;
use app\admin\model\Orangs;
use think\Exception;
use think\Session;
use app\admin\model\Index as IndexModel;
use app\admin\model\Wxpay;
class Orange extends  Api
{
    protected $noNeedLogin = ['canblak'];
    protected $noNeedRight = ['*'];

    /**
     * 橙券兑换
     */
    public function exchanginfo(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $qinghai  = 0; //青海类型
        $zone_id = input('zone_id');
        $class_id = input('class_id');
        $phones = input('phones');//号码
        if($userInfo['mobile'] != $phones){
            $this->error("领取号码与注册号码不一致");
        }
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        $item_id = $datainfo['resource_id'];
        $map['item_id'] = $item_id;
        $map['type'] = 8;
        $map['switch'] = 1;
        $num =1;
        $goodsInfo = Db::name("goods")->where($map)->find();
        if(!empty($goodsInfo)){
            if($goodsInfo['stock']<=0){
                Db::name("goods")->where(['item_id'=>$goodsInfo['item_id']])->setField("switch",0);//自动下架
                $this->error("商品已售罄,请明日再来");exit;
            }
            if($zone_id){
                $exchange_goods = Db::name('operator_exchange_goods')->where('vip_id', $userInfo['vip_id'])->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $item_id)->find();
                if($exchange_goods['xy'] == 1 || !$exchange_goods){
                    $this->error("商品下架,请明日再来");exit;
                }
                $activity_price_cent = $exchange_goods['vip_money'];//会员价价
            }
            if($activity_price_cent>0){
                $this->error("流程错误");exit;
            }
            $order_no = makeOrderNum();
            $params = [
                'user_mobile'=>$userInfo['mobile'],
                'mobile'=>$phones,
                'user_id'=>$userInfo['id'],
                'order_no'=>$order_no,
                'type'=>8,//橙券商品
                'resource_id'=>$item_id,
                'createtime'=>date('Y-m-d H:i:s'),
                'num'=>$num,
                'title'=>$goodsInfo['title'],
                'brand'=>$goodsInfo['brand'],
                'main_picture'=>$goodsInfo['main_picture'],
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'amount'=>0,
                'exchange_code'=>'',
                'price'=>round($goodsInfo['cb_price']/100,2),
            ];
            //是会员的话，打折
            $params['discount_amount'] =round($goodsInfo['original_price_cent']/100,2);
            $id = 0;
            if($zone_id){
                Db::startTrans();
                try {
                    $kc = Db::name('order')->where('zone_id',$zone_id)->where('class_id',$class_id)->where('resource_id',$item_id)->whereTime('createtime','today')->lock(true)->count();
                    $day_num = Db::name('operator_exchange_goods')->where('zone_id',$zone_id)->where('cla_id',$class_id)->where('resource_id',$item_id)->value('day_num');
                    if($kc >=$day_num){
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>'今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                }
            }
            if($sanfang){  //三方兑换验证
                Db::startTrans();
                try {
                    $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
                    if ($sanfang_vip) {
                        if($sanfang_vip['is_att'] == 3){
                            $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id',$zone_id)->where('is_do',0)->where('end_time','>',time())->lock(true)->find();
                            if(!$qinghao){
                                Db::rollback();
                                exit(json_encode(array('code' =>0, 'msg' =>'会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id',$qinghao['id'])->update(['is_do'=>1]);
                            $qinghai = $qinghao['id'];
                        }
                    } else {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
                    }
                    $params['from'] = 2;
                    $id = Db::name("order")->insertGetId($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                }
            }else {
                if ($zone_id) {
                    Db::startTrans();
                    try {
                        $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                        $operatorkcyz = Db::name('operator_exchange_goods')
                            ->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $item_id)
                            ->field('id,day_num,sy_num')
                            ->lock(true)
                            ->find();
                        if ($operatorkcyz['sy_num'] >= $operatorkcyz['day_num']) {
                            Db::rollback();
                            exit(json_encode(array('code' => 0, 'msg' => '今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
                        }
                        if ($operator_vip['type'] == 5) {
                            $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->lock(true)->find();
                            if (!$qinghao) {
                                Db::rollback();
                                exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id', $qinghao['id'])->update(['is_do' => 1]);
                            $qinghai = $qinghao['id'];
                        }
                        Db::name('operator_exchange_goods')->where('id', $operatorkcyz['id'])->setInc('sy_num');
                        $params['from'] = 2;
                        $id = Db::name("order")->insertGetId($params);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' => 0, 'msg' => $e), JSON_UNESCAPED_UNICODE));
                    }
                }
            }
            if($id){
                $order = Db::name('order')->where('id',$id)->find();
                $res =  Orangs::send($order['mobile'],$order['order_no'],$order['resource_id']);
                if($res['code'] == 7000){
                    Db::startTrans();
                    try {
                        Db::name("order")->where(['id'=>$id])->update([
                            'status'=>2,//已支付
                        ]);
                        Db::name('goods')->where('item_id',$order['resource_id'])->setInc('total_sales');
                        Db::name('goods')->where('item_id',$order['resource_id'])->setDec('stock');
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->success("兑换成功！~",$strArr);
                }else{
                    Db::name("order")->where(['order_no' => $order['order_no']])->update(['status' => 3]);
                    if($qinghai >0){
                        Db::name('qinghao')->where('id',$qinghai)->update(['is_do'=>0]);
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->success("兑换失败！~",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }else{
            $this->error("商品已售罄,请明日再来");
        }
    }
    /**
     * 会员购买
     */
    public function vipCq(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $qinghai = 0; //会员五  青海类型
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        //会员特殊购买
        $zone_id = $datainfo['zone_id'];
        $class_id = $datainfo['class_id'];
        $item_id = input('resource_id');
        if($zone_id){
            Db::startTrans();
            try {
                $kc = Db::name('order')->where('zone_id',$zone_id)->where('class_id',$class_id)->where('resource_id',$item_id)->whereTime('createtime','today')->lock(true)->count();
                $day_num = Db::name('operator_exchange_goods')->where('zone_id',$zone_id)->where('cla_id',$class_id)->where('resource_id',$item_id)->value('day_num');
                if($kc >=$day_num){
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>'今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
            }
        }
        if($sanfang){  //三方兑换验证
            $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
            if ($sanfang_vip) {
                if($sanfang_vip['is_att'] == 3){
                    $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            } else {
                exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
            }
        }else {
            if ($zone_id) {
                if (!$userInfo['vip_id']) {
                    $this->error("您还不是会员,请先购买会员吧！~");
                    exit;
                }
                $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                if ($operator_vip['type'] == 5) {
                    $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            }
        }
        $map['item_id'] = $item_id;
        $map['type'] = 8;
        $map['switch'] = 1;
        $num =1;
        $phones = input('phones');//号码
        if($userInfo['mobile'] != $phones){
            $this->error("领取号码与注册号码不一致");
        }
        $goodsInfo = Db::name("goods")->where($map)->find();
        if(!empty($goodsInfo)){
            if($goodsInfo['stock']<=0){
                Db::name("goods")->where(['item_id'=>$goodsInfo['item_id']])->setField("switch",0);//自动下架
                $this->error("商品已售罄,请明日再来");exit;
            }
            if($zone_id){
                $from = 2;
                $exchange_goods = Db::name('operator_exchange_goods')->where('vip_id',$userInfo['vip_id'])->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $item_id)->find();
                if($exchange_goods['xy'] == 1 || !$exchange_goods){
                    $this->error("商品下架,请明日再来");exit;
                }
                $original_price_cent = $exchange_goods['fsj'];//原价
                $activity_price_cent = $exchange_goods['vip_money'];//会员价价
            }
            if($activity_price_cent<=0){
                $this->error("流程错误");exit;
            }
            $order_no = makeOrderNum();
            $params = [
                'coupon_id'=>0,
                'user_mobile'=>$userInfo['mobile'],
                'mobile'=>$phones,
                'user_id'=>$userInfo['id'],
                'order_no'=>$order_no,
                'type'=>8,//橙券商品
                'resource_id'=>$item_id,
                'createtime'=>date('Y-m-d H:i:s'),
                'num'=>$num,
                'title'=>$goodsInfo['title'],
                'brand'=>$goodsInfo['brand'],
                'main_picture'=>$goodsInfo['main_picture'],
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'from'=>$from,
                'qing_id'=>$qinghai,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'exchange_code'=>'',
                'price'=>round($goodsInfo['cb_price']/100,2),
            ];
            $params['discount_amount'] = $original_price_cent - $activity_price_cent;
            $amount =$activity_price_cent;
            $params['amount'] = $amount;
            $id = Db::name("order")->insertGetId($params);
            if($id){
                //---微信支付---
                if ($amount > 0) {
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$order_no
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/cqzcpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }else{
            $this->error("商品已售罄,请明日再来");
        }
    }


    /**
     *  橙券正常购买
     */
    public function cqorder(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $operator_id= Db::name('operator')->where('name',$userInfo['operator'])->value('id');
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        $item_id =$datainfo['resource_id'];
        $map['item_id'] = $item_id;
        $map['type'] = 8;
        $map['switch'] = 1;
        $num = 1;
        $phones =$datainfo['phones'];//号码
        $goods_type = Db::name('goods')->where('item_id',$item_id)->value('goods_type');
        if($goods_type == 1){
            $cbxzorder =IndexModel::cbxzorder($item_id,$userInfo['id']);
            if($cbxzorder == 1){
                $this->error("今日已售罄,请明日再来");
            }
        }else{
            $ddxzorder =IndexModel::ddxzorder($item_id,$userInfo['mobile']);
            if($ddxzorder == 1){
                $this->error("今日已售罄,请明日再来");
            }
        }
        $goodsInfo = Db::name("goods")->where($map)->find();
        if(!empty($goodsInfo)){
            if($goodsInfo['stock']<=0){
                Db::name("goods")->where(['item_id'=>$goodsInfo['item_id']])->setField("switch",0);//自动下架
                $this->error("商品已售罄,请明日再来");exit;
            }
            //计算实际支付价格
            $original_price_cent = $goodsInfo['original_price_cent'] * $num;//原价
            $activity_price_cent = $goodsInfo['activity_price_cent'] * $num;//活动价
            $order_no = makeOrderNum();
            $params = [
                'operator_id'=>$operator_id,
                'user_mobile'=>$userInfo['mobile'],
                'mobile'=>$phones,
                'user_id'=>$userInfo['id'],
                'order_no'=>$order_no,
                'type'=>8,//橙券商品
                'resource_id'=>$item_id,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$num,
                'title'=>$goodsInfo['title'],
                'brand'=>$goodsInfo['brand'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'price'=>round($goodsInfo['cb_price']/100,2),
            ];
            //是会员的话，打折
            $amount =$activity_price_cent;
            $amount = round($amount/100,2);//转为正常价格,因为数据库里存的是分
            $params['discount_amount'] = round($original_price_cent/100,2) - $amount;
            $params['amount'] = $amount;
            //阿里订单创建并返回支付参数
            $id = Db::name("order")->insertGetId($params);
            if($id){
                if($amount>0){
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$order_no
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/cqzcpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info,$userInfo['gzh_open_id']);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else {
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }else{
            $this->error("商品已售罄,请明日再来");
        }

    }
    /**
     * 橙券卡密
     */
    public function cqkmorder(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $operator_id = Db::name('operator')->where('name',$userInfo['operator'])->value('id');
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        $item_id =$datainfo['resource_id'];
        $this->stock($item_id);
        $map['item_id'] = $item_id;
        $map['type'] = 9;
        $map['switch'] = 1;
        $num = 1;
        $goods_type = Db::name('goods')->where('item_id',$item_id)->value('goods_type');
        if($goods_type == 1){
            $cbxzorder =IndexModel::cbxzorder($item_id,$userInfo['id']);
            if($cbxzorder == 1){
                $this->error("今日已售罄,请明日再来");
            }
        }else{
            $ddxzorder =IndexModel::ddxzorder($item_id,$userInfo['mobile']);
            if($ddxzorder == 1){
                $this->error("今日已售罄,请明日再来");
            }
        }
        $goodsInfo = Db::name("goods")->where($map)->find();
        if(!empty($goodsInfo)){
            if($goodsInfo['stock']<=0){
                Db::name("goods")->where(['item_id'=>$goodsInfo['item_id']])->setField("switch",0);//自动下架
                $this->error("商品已售罄,请明日再来");exit;
            }
            //计算实际支付价格
            $original_price_cent = $goodsInfo['original_price_cent'] * $num;//原价
            $activity_price_cent = $goodsInfo['activity_price_cent'] * $num;//活动价
            $order_no = makeOrderNum();
            $params = [
                'operator_id'=>$operator_id,
                'user_mobile'=>$userInfo['mobile'],
                'user_id'=>$userInfo['id'],
                'order_no'=>$order_no,
                'type'=>9,//橙券卡密商品
                'resource_id'=>$item_id,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$num,
                'title'=>$goodsInfo['title'],
                'brand'=>$goodsInfo['brand'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'price'=>round($goodsInfo['cb_price']/100,2),
            ];
            //是会员的话，打折
            $amount =$activity_price_cent;
            $amount = round($amount/100,2);//转为正常价格,因为数据库里存的是分
            $params['discount_amount'] = round($original_price_cent/100,2) - $amount;
            $params['amount'] = $amount;
            //阿里订单创建并返回支付参数
            $id = Db::name("order")->insertGetId($params);
            if($id){
                if($amount>0){
                    //需要支付,获取微信支付参数
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$order_no
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/cqkmpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else {
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }else{
            $this->error("商品已售罄,请明日再来");
        }
    }

    /**
     * 橙券卡密兑换
     */
    public function exchangkminfo(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        $qinghai  = 0; //青海类型
        $zone_id =$datainfo['zone_id'];//会员兑换
        $class_id = $datainfo['class_id'];
        $item_id =$datainfo['resource_id'];
        $this->stock($item_id);
        if($zone_id){
            Db::startTrans();
            try {
                $kc = Db::name('order')->where('zone_id',$zone_id)->where('class_id',$class_id)->where('resource_id',$item_id)->whereTime('createtime','today')->lock(true)->count();
                $day_num = Db::name('operator_exchange_goods')->where('zone_id',$zone_id)->where('cla_id',$class_id)->where('resource_id',$item_id)->value('day_num');
                if($kc >=$day_num){
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>'今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
            }
        }
        $map['item_id'] = $item_id;
        $map['type'] = 9;
        $map['switch'] = 1;
        $num = 1;
        $goodsInfo = Db::name("goods")->where($map)->find();
        if(!empty($goodsInfo)){
            if($goodsInfo['stock']<=0){
                Db::name("goods")->where(['item_id'=>$goodsInfo['item_id']])->setField("switch",0);//自动下架
                $this->error("商品已售罄,请明日再来");exit;
            }
            if($zone_id){
                $exchange_goods = Db::name('operator_exchange_goods')->where('vip_id', $userInfo['vip_id'])->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $item_id)->find();
                if($exchange_goods['xy'] == 1 || !$exchange_goods){
                    $this->error("商品下架,请明日再来");exit;
                }
                $activity_price_cent = $exchange_goods['vip_money'];//会员价价
            }
            if($activity_price_cent>0){
                $this->error("流程错误");exit;
            }
            $order_no = makeOrderNum();
            $params = [
                'user_mobile'=>$userInfo['mobile'],
                'user_id'=>$userInfo['id'],
                'order_no'=>$order_no,
                'type'=>9,//橙券卡密
                'resource_id'=>$item_id,
                'createtime'=>date('Y-m-d H:i:s'),
                'num'=>$num,
                'title'=>$goodsInfo['title'],
                'brand'=>$goodsInfo['brand'],
                'main_picture'=>$goodsInfo['main_picture'],
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'amount'=>0,
                'exchange_code'=>'',
                'price'=>round($goodsInfo['cb_price']/100,2),
            ];
            //是会员的话，打折
            $params['discount_amount'] =round($goodsInfo['original_price_cent']/100,2);
            $id = 0;
            if($sanfang){  //三方兑换验证
                Db::startTrans();
                try {
                    $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
                    if ($sanfang_vip) {
                        if($sanfang_vip['is_att'] == 3){
                            $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id',$zone_id)->where('is_do',0)->where('end_time','>',time())->lock(true)->find();
                            if(!$qinghao){
                                Db::rollback();
                                exit(json_encode(array('code' =>0, 'msg' =>'会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id',$qinghao['id'])->update(['is_do'=>1]);
                            $qinghai = $qinghao['id'];
                        }
                    } else {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
                    }
                    $params['from'] = 2;
                    $id = Db::name("order")->insertGetId($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                }
            }else {
                if ($zone_id) {
                    if (!$userInfo['vip_id']) {
                        $this->error("您还不是会员,请先购买会员吧！~");
                        exit;
                    }
                    Db::startTrans();
                    try {
                        $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                        $operatorkcyz = Db::name('operator_exchange_goods')
                            ->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $item_id)
                            ->field('id,day_num,sy_num')
                            ->lock(true)
                            ->find();
                        if ($operatorkcyz['sy_num'] >= $operatorkcyz['day_num']) {
                            Db::rollback();
                            exit(json_encode(array('code' => 0, 'msg' => '今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
                        }
                        if ($operator_vip['type'] == 5) {
                            $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->lock(true)->find();
                            if (!$qinghao) {
                                Db::rollback();
                                exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                            }
                            Db::name('qinghao')->where('id', $qinghao['id'])->update(['is_do' => 1]);
                            $qinghai = $qinghao['id'];
                        }
                        Db::name('operator_exchange_goods')->where('id', $operatorkcyz['id'])->setInc('sy_num');
                        $params['from'] = 2;
                        $id = Db::name("order")->insertGetId($params);
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' => 0, 'msg' => $e), JSON_UNESCAPED_UNICODE));
                    }
                }
            }
            if($id){
                $order = Db::name('order')->where('id',$id)->find();
                $res =  Orangs::ksend($order['num'],$order['resource_id']);
                if($res['code'] == 7000){
                    Db::startTrans();
                    try {
                        foreach ($res['data'] as &$v) {
                            Auth::kmjx($order, $v);
                        }
                        //完成支付
                        Db::name("order")->where(['order_no' => $order_no])->update([
                            'status' => 4,
                            'biz_order_id' => $order_no
                        ]);
                        Db::name('goods')->where('item_id', $order['resource_id'])->setInc('total_sales');
                        Db::name('goods')->where('item_id', $order['resource_id'])->setDec('stock');
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->success("购买成功！~",$strArr);
                }else{
                    Db::name("order")->where(['order_no' => $order['order_no']])->update(['status' => 3]);
                    if($qinghai >0){
                        Db::name('qinghao')->where('id',$qinghai)->update(['is_do'=>0]);
                    }
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败！~",$strArr);
                }

            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }else{
            $this->error("商品已售罄,请明日再来");
        }
    }

    /**
     * 橙券卡密会员购买
     */
    public function vipCqkm(){
        $user_id = $this->auth->id;
        $userInfo  = Auth::userInfo($user_id);
        $qinghai = 0; //会员五  青海类型
        $datainfo = IndexModel::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        if(!isset($datainfo['sanfang'])){
            $datainfo['sanfang'] = 0;
        }
        $sanfang =$datainfo['sanfang'];//三方
        if($sanfang){
            $vip_id = $datainfo['vip_id'];
            $userInfo['vip_id'] = $vip_id;
        }
        if($userInfo['vip_id']){
            $operator_id =   Db::name('operator_vip')->where('id',$userInfo['vip_id'])->value('operator_id');
        }else{
            $operator_id = 1;
        }
        $item_id =$datainfo['resource_id'];
        $this->stock($item_id);
        //会员特殊购买
        $zone_id = $datainfo['zone_id'];
        $class_id = $datainfo['class_id'];
        if($zone_id){
            Db::startTrans();
            try {
                $kc = Db::name('order')->where('zone_id',$zone_id)->where('class_id',$class_id)->where('resource_id',$item_id)->whereTime('createtime','today')->lock(true)->count();
                $day_num = Db::name('operator_exchange_goods')->where('zone_id',$zone_id)->where('cla_id',$class_id)->where('resource_id',$item_id)->value('day_num');
                if($kc >=$day_num){
                    Db::rollback();
                    exit(json_encode(array('code' =>0, 'msg' =>'今日已售罄，请明日再来'), JSON_UNESCAPED_UNICODE));
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                exit(json_encode(array('code' =>0, 'msg' =>$e), JSON_UNESCAPED_UNICODE));
            }
        }
        if($sanfang){  //三方兑换验证
            $sanfang_vip = Db::name("sanfang_vip")->where('vip_id',$vip_id)->where(['mobile' => $userInfo['mobile']])->where('is_t', 0)->find();
            if ($sanfang_vip) {
                if($sanfang_vip['is_att'] == 3){
                    $qinghao = Db::name('qinghao')->where('mobile',$userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            } else {
                exit(json_encode(array('code' =>0, 'msg' =>'您未加入该会员'), JSON_UNESCAPED_UNICODE));
            }
        }else {
            if ($zone_id) {
                $operator_vip = Db::name('operator_vip')->where('id', $userInfo['vip_id'])->field('id,type,exchange_count,rules')->find();
                if ($operator_vip['type'] == 5) {
                    $qinghao = Db::name('qinghao')->where('mobile', $userInfo['mobile'])->where('zone_id', $zone_id)->where('is_do', 0)->where('end_time', '>', time())->find();
                    if (!$qinghao) {
                        exit(json_encode(array('code' => 0, 'msg' => '会员兑换权益已用完！'), JSON_UNESCAPED_UNICODE));
                    }
                    $qinghai = $qinghao['id'];
                }
            }
        }
        $map['item_id'] = $item_id;
        $map['type'] = 9;
        $map['switch'] = 1;
        $num = 1;
        $goodsInfo = Db::name("goods")->where($map)->find();
        if(!empty($goodsInfo)){
            if($goodsInfo['stock']<=0){
                Db::name("goods")->where(['item_id'=>$goodsInfo['item_id']])->setField("switch",0);//自动下架
                $this->error("商品已售罄,请明日再来");exit;
            }
            if($zone_id) {
                $from = 2;
                $exchange_goods = Db::name('operator_exchange_goods')->where('vip_id',$userInfo['vip_id'])->where('zone_id', $zone_id)->where('cla_id', $class_id)->where('resource_id', $item_id)->find();
                if($exchange_goods['xy'] == 1 || !$exchange_goods){
                    $this->error("商品下架,请明日再来");exit;
                }
                $original_price_cent = $exchange_goods['fsj'];//原价
                $activity_price_cent = $exchange_goods['vip_money'];//会员价价
            }
            if($activity_price_cent<=0){
                $this->error("流程错误");exit;
            }
            $order_no = makeOrderNum();
            $params = [
                'user_mobile'=>$userInfo['mobile'],
                'user_id'=>$userInfo['id'],
                'order_no'=>$order_no,
                'type'=>9,//橙券卡密
                'resource_id'=>$item_id,
                'createtime'=>date('Y-m-d H:i:s'),
                'coupon_id'=>0,
                'num'=>$num,
                'title'=>$goodsInfo['title'],
                'brand'=>$goodsInfo['brand'],
                'main_picture'=>$goodsInfo['main_picture'],
                'flash_sale_id'=>0,//渺少ID
                'zone_id'=> $zone_id,
                'class_id'=> $class_id,
                'operator_id'=>$operator_id,
                'vip_id'=>$userInfo['vip_id'],
                'from'=>$from,
                'exchange_code'=>'',
                'qing_id'=>$qinghai,
                'price'=>round($goodsInfo['cb_price']/100,2),
            ];
            $params['discount_amount'] = $original_price_cent - $activity_price_cent;
            $amount =$activity_price_cent;
            $params['amount'] = $amount;
            $id = Db::name("order")->insertGetId($params);
            if($id){
                if ($amount > 0) {
                    $res=[
                        'order_amount'=>$amount,
                        'order_sn'=>$order_no
                    ];
                    $notify_urls="http://".$_SERVER['HTTP_HOST']."/api/wechat_notify/cqkmpay";
                    $Info = 'H5订单支付';
                    $objectxml = Wxpay::wx_pay_zh($res,$notify_urls,$Info);
                    if($objectxml['return_code'] == 'FAIL'){
                        Db::name('order')->where('id',$id)->update(['status'=>3]);
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                        $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                    }else{
                        $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id,'result'=>$objectxml]));
                        $this->success("购买成功！~",$strArr);
                    }
                }else{
                    Db::name('order')->where('id',$id)->update(['status'=>3]);
                    $strArr=  IndexModel::setLongEncrypt(Config::get("miyao.gong"),json_encode(['order_id'=>$id]));
                    $this->error("购买失败,请咨询在线客服：4008772758",$strArr);
                }
            }else{
                $this->error("创建订单失败,请联系客服！~");
            }
        }else{
            $this->error("商品已售罄,请明日再来");
        }
    }


    public function stock($goods_no){
        $res =  Orangs::stock($goods_no);
        if($res['code']  == 7000){
           if($res['data']['stock_num'] <= 0){
               $this->error("商品已售罄,请明日再来");
           }
        }else{
            $this->error("商品已售罄,请明日再来");
        }
    }


    /**
     * 回调
     */
    public function canblak(){
        $info = input('post.');
        Db::name('orange_canblak')->insert($info);
        if($info['state'] == 'SUCCESS'){
            Db::name('order')->where('order_no',$info['order_no'])->update(['status'=>4]);
        }else if($info['state'] == 'FAILURE'){
            Db::name('order')->where('order_no',$info['order_no'])->update(['status'=>3]);
        }
        echo 'ok';
    }



}